package org.example;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


public class base64text {

    private static final String API_URL = "http://192.168.1.101:8080/api/base64";   //固定ip和端口的接口

    /*
    * sendBase64String(String base64String){}
    * 此方法用于将base64字符串发送对应ip的打标机开放的接口
    * */
    public static void sendBase64String(String base64String) {
        try {
            // 创建URL对象
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和内容类型
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
            connection.setDoOutput(true);

            // 获取输出流并写入Base64字符串
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] inputBytes = base64String.getBytes("UTF-8");
                outputStream.write(inputBytes);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            // 读取响应
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }

                    // 打印响应
                    System.out.println("Response: " + response.toString());
                }
            } else {
                System.out.println("POST 请求不在工作 ！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /* 由于string类型无法存入非常大的base64字符串，继而将base64字符串先放入txt文件中读取
     * readResourceFile(String fileName){}
     * 此方法用于读取txt中的base64字符串
     * */
    public static String readResourceFile(String fileName) {
        StringBuilder contentBuilder = new StringBuilder();
        try {
            Path path = Paths.get(base64text.class.getResource("/" + fileName).toURI());
            List<String> lines = Files.readAllLines(path);
            for (String line : lines) {
                contentBuilder.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentBuilder.toString();
    }


    public static void main(String[] args) {
        // 从文件中读取Base64字符串
        String longBase64String = readResourceFile("base64.txt");   //文件存入resources目录下面

        // 调用发送方法
        sendBase64String(longBase64String);
    }
}
